package com.miao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miao.dto.CourseCategoryDto;
import com.miao.mapper.CourseCategoryMapper;
import com.miao.pojo.CourseCategory;
import com.miao.service.ICourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements ICourseCategoryService {
    @Autowired
    private CourseCategoryMapper categoryMapper;

    @Override
    public List<CourseCategoryDto> queryCategoryOfCourese(String id) {
        ArrayList<CourseCategoryDto> result = new ArrayList<>();
        //对所有分类进行查询
        List<CourseCategoryDto> courseCategoryDtos = categoryMapper.queryCourseCategory(id);
        //找到各个节点的子节点，封装为List<CourseCategoryDto>
        //1.将List转化为Map,方便直接取父节点
        HashMap<String, CourseCategoryDto> courseCategoryHashMap = new HashMap<>();
        for (CourseCategoryDto courseCategoryDto : courseCategoryDtos) {
            if(courseCategoryDto.getId().equals(id) == false) {//根节点不放进去
                courseCategoryHashMap.put(courseCategoryDto.getId(), courseCategoryDto);
            }
        }
        //2.遍历mapper返回的列表，对父节点是根节点的放到结果集，其他的，放入自己父节点的children
        for (CourseCategoryDto courseCategoryDto : courseCategoryDtos) {
            if(courseCategoryDto.getId().equals(id) == true)continue;//当前节点是根节点
            else if(courseCategoryDto.getParentid().equals(id) == true){
                result.add(courseCategoryDto);//当前节点是根节点的子节点
            }else{
                CourseCategoryDto parent = courseCategoryHashMap.get(courseCategoryDto.getParentid());
                if(parent.getChildrenTreeNodes() == null){
                    parent.setChildrenTreeNodes(new ArrayList<CourseCategoryDto>());
                }
                List<CourseCategoryDto> childrenTreeNodes = parent.getChildrenTreeNodes();
                childrenTreeNodes.add(courseCategoryDto);//找到父节点的list，加入
            }
        }

        return result;
    }
}
